<?php

namespace app\index\controller;

use app\data\model\ActActivity;
use app\data\model\ActActivityDiy;
use app\data\model\ActActivityGuest;
use app\data\model\ActActivityTicket;
use app\data\model\ActEamilLog;
use app\data\model\ActEmailNotice;
use app\data\model\ActOrder;
use app\data\model\ActOrganizer;
use app\data\model\ActSettingTheme;
use app\data\model\ActSettingType;
use app\data\model\ActTicketDetails;
use app\data\model\ActTicketGroup;
use app\data\model\ActUserModel;
use app\data\model\DataUser;
use app\index\service\EmailService;
use app\index\service\LoginUserService;
use think\facade\Db;

class UserActivity extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $this->needLogin();
        
    }

    public function index()
    {
        $this->acts = ActActivity::where('create_user_id', LoginUserService::get('id'))
            ->withCount(['OrderModel'=>function($query,&$alias){
                $query->where('status',1);
                $alias = "order_count";
            }])
            ->order('id desc')
            ->limit(10)
            ->append(['creator_name','status_name','ticket_count','state'])
            ->select();
        //  $this->user   = DataUser::where('id',LoginUserService::get('id'))->field('id,name,email,profile')->find();
        //  $this->companys = array_unique(array_column($this->acts->toArray(),'organizer_name'));
         $this->companys = ActOrganizer::where('uid',LoginUserService::get('id'))->field('id,name')->select();
        $this->fetch();
    }

    /**
     * @name:权限
     * @author:Sam
     * @date:2024-04-16
     * @param:[string] param [desc]
    */
    public function active_role(){
        if(!in_array(1,$this->user['roles'])) $this->error('没有权限');
        $this->pid =  LoginUserService::get('id') ?? 0;
        if(request()->isGet()){
            $this->user_list = ActUserModel::where('id',LoginUserService::get('id'))->whereOr('pid',LoginUserService::get('id'))->field('id,profile,pid,name,email,roles')->select()->toArray();
            $this->fetch();
        }else{
            $data = $this->_vali([
                'data.require'        => '数据不得為空',
            ]);
            $role_data = $data['data'];
            $role_data_arr  = json_decode($role_data,true);
            if(!is_array($role_data_arr) || !count($role_data_arr)) $this->error('数据格式不正确');
            foreach ($role_data_arr as $key => $value) {
                if(empty($value['uid']) || empty($value['role'])) $this->error('数据格式不正确');
                if($value['uid'] == LoginUserService::get('id')) continue;
                ActUserModel::where('id',$value['uid'])->update([
                    'roles' => implode(',',$value['role'])
                ]);
            }
            $this->success('操作成功');
        }

    }

  

    /**
     * @name:活动列表
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function list(){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $uids = [$this->user['id']]; 
        if($this->user['pid'] > 0){
            array_push($uids,$this->user['pid']);
        }
        $this->acts = ActActivity::where('create_user_id','in', $uids)
        ->order('id desc')
        ->withCount(['OrderModel'=>function($query,&$alias){
            $query->where('status',1);
            $alias = "order_count";
        }])
        ->append(['creator_name','status_name','ticket_count','state'])
        ->select();
        $this->is_verify = ActActivity::where('create_user_id', LoginUserService::get('id'))->where('status',0)->where('is_draft',0)->count();
        $this->all       = ActActivity::where('create_user_id', LoginUserService::get('id'))->where('is_draft',0)->count();
        $this->publishs  = ActActivity::where('create_user_id', LoginUserService::get('id'))->where('status',1)->where('is_draft',0)->count();
        $this->offstate  = ActActivity::where('create_user_id', LoginUserService::get('id'))->where('status',3)->where('is_draft',0)->count();
        $this->fetch();
    }


    /**
     * @name:下架
     * @author:Sam
     * @date:2024-04-12
     * @param:[string] param [desc]
    */
    public function offsale($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = ActActivity::where('id',$id)->where('create_user_id', LoginUserService::get('id'))
        ->order('id desc')
        ->find();
        if(request()->isPost()){
            $this->act->setAttrs(['status'=>3]);
            $this->act->save();
            return $this->success('操作成功');
        }
        return $this->error('请求错误');
    }

 
        /**
     * @name:角色
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function role(){
        if(!in_array(3,$this->user['roles'])) $this->error('没有权限');
        $this->acts = ActActivity::where('create_user_id', LoginUserService::get('id'))
        ->order('id desc')
        ->select()
        ->append(['creator_name']);
         $this->fetch();
    }
    

    /**
     * @name:角色添加
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function active_role_add(){
        if(!in_array(3,$this->user['roles'])) $this->error('没有权限');
        $this->acts = ActActivity::where('create_user_id', LoginUserService::get('id'))
        ->order('id desc')
        ->select()
        ->append(['creator_name']);
         $this->fetch();
    }

    /**
     * @name:主办单位
     * @author:Sam
     * @date:2024-04-15
     * @param:[string] param [desc]
    */
    public function  organizer(){
        if(!in_array(1,$this->user['roles'])) $this->error('没有权限');
        // $this->organizer = ActOrganizer::where('uid',LoginUserService::get('id'))->select();
        if(request()->isGet()){
            if($id = input('id/d',0) !=0){
                $this->organizer = ActOrganizer::where('uid',LoginUserService::get('id'))->where('id',$id)->find();
            }
            return $this->fetch();
        }else{
            $data = request()->post();
            if( empty($data['id'])){
                if(ActOrganizer::where('uid',LoginUserService::get('id'))->where('name',$data['name'])->count()) return $this->error('名称已存在');
                $data['uid'] = LoginUserService::get('id');
                if( ActOrganizer::create($data)) return $this->success('操作成功');
                return $this->error('操作失败');
            }else{
                if(ActOrganizer::where('uid',LoginUserService::get('id'))->where('id','<>',$data['id'])->where('name',$data['name'])->count()) return $this->error('名称已存在');
                if(!$ActOrganizer = ActOrganizer::where('uid',LoginUserService::get('id'))->where('id',$data['id'])->find()) return $this->error('数据不存在');
                if($ActOrganizer->save($data))  return $this->success('操作成功');
                return $this->error('操作失败');
            }
            
        }
       
    }


    /**
     * @name:票券资讯
     * @author:Sam
     * @date:2024-04-11
     * @param:[string] param [desc]
    */
    public function user_ticket($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        $this->act->append(['status_name','remain_ticket']);
        $this->ticket = $this->act->ticketModel()->find();
        $this->ticket_detail = ActTicketDetails::with(['ticketModel'])->withCount(['orders' => function($query) {
            $query->where('status',1);
        }])->withSum(['orders' => function($query, &$alias) {
            $query->where('status',1);
        }],'price')->where('activity_id',$id)->append(['sale_status'])->select()->toArray();
        $this->ticket_group          = ActTicketGroup::where('activity_id',$id)->append(['sale_status'])->withCount(['orders' => function($query) {
            $query->where('status',1);
        }])->withSum(['orders' => function($query, &$alias) {
            $query->where('status',1);
        }],'price')->select();
        $this->success_tickets       = ActOrder::where('activity_id',$id)->where('status',1)->count();
        $this->success_ticket_amount = ActOrder::where('activity_id',$id)->where('status',1)->sum('price');
        $this->id = $id;
        $this->fetch();
    }

    /**
     * @name:报名人员
     * @author:Sam
     * @date:2024-04-11
     * @param:[string] param [desc]
    */
    public function user_active_par_list($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        $this->id = $id;
        if(request()->isGet()){
            if(input('get.act') == 'download'){
                $search = request()->param();
                $wheres = [];
                $wheres[] = ['activity_id','=',$id];
                if(isset($search['searchword']) && $search['searchword'] !=''){
                    $wheres[] = ['nickname|mobile','like',"%{$search['searchword']}%"];
                }
                if(isset($search['status']) && $search['status'] !=''){
                    $wheres[] = ['status','=',$search['status']];
                }
                if(isset($search['group']) && $search['group'] > 0){
                    $wheres[] = ['group_id','=',$search['group']];
                }
                $title = ['编号', '创建时间','价格','票券','状态','用户','邮箱','电话','报名姓名','报名邮箱','报名手机'];
                set_time_limit(0); // 设置超时时间
                $filename = '報名名單' . date('Ymdhis') . '.csv';
                header("Content-type:application/vnd.ms-csv");
                header('content-disposition:attachment; filename="' . $filename . '"');
                ob_end_flush();
                echo iconv('utf-8', 'gbk', implode(',', $title)) . PHP_EOL;
                $lastId = 0;
                // dump($wheres);die;
                while (true) {
                    $list =  ActOrder::with('user')->where($wheres)->limit(100)->order('id asc')->where('id','>',$lastId)->field('id,sn,create_time,activity_id,price,ticket_name,status,name,email,phone,buy_user_id,group_id')->append(['status_name'])->select()->toArray();   
                 
                    if (!empty($list)) {
                      
                        foreach ($list as $order) {
                            $item = []; // 初始化数组
                            // 用户信息
                            $item[] = $order['sn']; 
                            $item[] = $order['create_time']; 
                            $item[] = $order['price']; 
                            $item[] = $order['ticket_name']; 
                            $item[] = $order['status_name']; 
                            $item[] = $order['user']['name']; 
                            $item[] = $order['user']['email']; 
                            $item[] = $order['user']['phone']; 
                            $item[] = $order['name']; 
                            $item[] = $order['email']; 
                            $item[] = $order['phone']; 
                            // dump($item);die;
                            // 写入内容
                            echo iconv('utf-8', 'gbk//IGNORE', implode(',', $item)) . PHP_EOL;
                            $lastId = $order['id']; // 最大id
                        }

                    } else {
                        break;
                    }
                }
                    exit;  
            }else{
                $query = input('get.');
                $where = [];
                $statusMappingSearch = [];
                $where[] = ['activity_id','=',$id];
                $statusMappingSearch[] = ['activity_id','=',$id];
                if(isset($query['status']) && $query['status'] != ''){
                    $where[] =  ['status','=',$query['status']];
                }else{
                    $query['status']  = 3;
                }
                if(isset($query['group']) && $query['group'] != '' && $query['group'] !=0){
                    $where[] =  ['group_id','=',$query['group']];
                    $statusMappingSearch[] =  ['group_id','=',$query['group']];
                }else{
                    $query['group']   = 0;
                }
                
                if(isset($query['keyword']) && $query['keyword'] != ''){
                    $where[] =  ['name|email|phone|ticket_name|sn','like',"%{$query['keyword']}%"];
                    $statusMappingSearch[] =  ['name|email|phone|ticket_name|sn','like',"%{$query['keyword']}%"];
                }else{
                    $query['keyword']   = '';
                }
                $limit = request()->get('limit',10);
                $query['limit']   = $limit;
                $this->query      = $query;
                $this->query_json = json_encode($query);
                $this->orders     = ActOrder::with(['diy'])->where($where)->append(['status_name','diy_data'])->order('id desc')->paginate([
                    'list_rows' => $limit,
                    'query'     => request()->get(),
                ]);
           
                $this->page   = $this->orders->render();
                $this->groups = ActTicketGroup::where('activity_id',$id)->select();
                $this->statusMapping = [
                    ['code' => 1, 'text' => '已创建','count' => 0],
                    ['code' => 2, 'text' => '已支付','count' => 0],
                    ['code' => 3, 'text' => '待审核','count' => 0],
                    ['code' => 4, 'text' => '已出票','count' => 0],
                    ['code' => 5, 'text' => '已退款','count' => 0],
                    ['code' => 6, 'text' => '无效','count' => 0]
                    // 添加更多状态映射根据您的需求
                ];
                foreach ($this->statusMapping as $key => &$value) {
                    $value['count'] = ActOrder::where($statusMappingSearch)->where('status',$value['code'])->count();
                }
                $this->fetch();
            }
        }else{
            $data = $this->_vali([ 
                'status.require'         => '狀態不得為空',
                'order_id.require'       => '訂單不得為空',
            ]);
            if(!in_array($data['status'],[4,6])) return $this->error('狀態异常');
            if(!$order = ActOrder::where('activity_id',$id)->where('id',$data['order_id'])->find())  return $this->error('未找到訂單');
            $order->status = $data['status'];
            $order->update_time = time();
            if($order->save()) return $this->success('操作成功');
            return $this->error('操作失敗');
        }
        
    }

    /**
     * @name:添加通知
     * @author:Sam
     * @date:2024-04-11
     * @param:[string] param [desc]
    */
    public function user_active_par_notice_add($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if(request()->isGet()){
            $send_type = input('get.send_type/d',0);
            if($send_type > 0){
                $count_list = 0;
                 if($send_type == 1){
                    //已报名待审核者
                    $count_list = ActOrder::where('activity_id',$id)->where('status',3)->count();
                 }elseif($send_type == 2){
                    //已报名成功者
                    $count_list = ActOrder::where('activity_id',$id)->where('status',4)->count();
                 }elseif($send_type == 3){
                    //已报名失败
                    $count_list = ActOrder::where('activity_id',$id)->where('status',6)->count();
                 }
                 return $this->success('ok',compact('count_list'));
            }else{
                $this->act->append(['status_name',]);
                $this->ticket = $this->act->ticketModel()->find();
                $this->id = $id;
                $this->fetch();
            }
        }else{
            $data = $this->_vali([
                'email.require'         => '郵箱不得為空',
                'title.require'         => '主題不得為空',
                'content.require'       => '內容不得為空',
                'send_type.require'     => '發送對象不得為空',
            ]);
            $reserve = request()->post('reserve',0);
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['send_count']  = 0;
            try {
                if($reserve == 1){
                    $send_date = input('post.send_date','');
                    $send_time = input('post.send_time','');
                    if($send_date == '') return $this->error('預約日期不得為空');
                    if($send_time == '') return $this->error('預約時間不得為空');
                    $send_time_arr = explode('-',$send_time);
                    $data['send_start']    = strtotime($send_date.' '.$send_time[0]);
                    $data['send_end']      = strtotime($send_date.' '.$send_time[1]);
                }
                $user_list = [];
                if($data['send_type'] == 1){
                    $user_list = ActOrder::with('user')->where('activity_id',$id)->where('status',3)->field('id,ticket_name,buy_user_id')->select();
                }elseif($data['send_type'] == 2){
                    $user_list = ActOrder::with('user')->where('activity_id',$id)->where('status',4)->field('id,ticket_name,buy_user_id')->select();
                }elseif($data['send_type'] == 3){
                    $user_list = ActOrder::with('user')->where('activity_id',$id)->where('status',6)->field('id,ticket_name,buy_user_id')->select();
                }else{
                    $user_list = ActOrder::with('user')->where('activity_id',$id)->field('id,ticket_name,buy_user_id')->select();
                }
                foreach ($user_list as $key => $value) {
                    if(isset($value['user']['email'])){
                        $email = $value['user']['email'];
                        if($reserve == 0){
                            //立即发送
                            $res = EmailService::sendHtml($email,$data['title'],"<p>欢迎注册本网站，您的邮箱验证码为{$data['content']}</p><p>如果有任何疑問或諮詢，請聯系 {$data['email']}</p>");
                            if($res){
                                $data['status'] = 1;
                                $data['send_count'] += 1;
                            }
                        } else{
                                $data['send_count'] += 1;
                                $data['finish_time'] = time();
                        }
                    }
                }
                ActEmailNotice::create([
                    'title'        => $data['title'],
                    'finish_time'  => time(),
                    'activity_id'  => $id,
                    'email'        => $data['email'],
                    'send_type'    => $data['send_type'],
                    'send_email'   => $email,
                    'send_count'   => $data['send_count'],
                    'content'      => $data['content']
                ]);
            } catch (\Exception $e) {
                 return $this->error($e->getMessage());
            }
                 return $this->success('操作成功');
  
        }
    }

    /**
     * @name:主动出票
     * @author:Sam
     * @date:2024-04-11
     * @param:[string] param [desc]
    */
    public function user_active_par_tick($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if(request()->isGet()){
            $this->act->append(['region_name']);
            $this->id = $id;
            $this->ticket_detail = ActTicketDetails::where('activity_id',$id)->append(['sale_status'])->where('rest_quantity','>',0)->select()->toArray();
            // dump($this->ticket_detail);die;
            $this->ticket_group  = ActTicketGroup::where('activity_id',$id)->append(['sale_status'])->where('group_remain_number','>',0)->select();
            $this->fetch();
        }else{
            $data = $this->_vali([
                'ticket_id.require'   => '票券不得為空',
                'ticket_type.require' => '票券不得為空',
                'email_list.require'  => '邀請名單不得為空',
            ]);
            if($data['ticket_type'] == 1){
                $ticket     = ActTicketDetails::find($data['ticket_id']);
                $ticket_name = $ticket->name;
            }else{
                $ticket     = ActTicketGroup::find($data['ticket_id']);
                $ticket_name = $ticket->group_name;
            }
            
            if(!$ticket) return $this->error('票券不存在');
            $email_list = json_decode($data['email_list'],true);
            if(!count($email_list)) $this->error('邀請名單格式不正確');
            $seenNames = [];
            // 遍历数组判断是否有相同名字
            foreach ($email_list as $person) {
                $name = $person['email'];
                // 检查这个名字是否已经存在
                if (in_array($name, $seenNames)) {
                    // 如果名字已经存在，标志为真
                    return  $this->error('郵箱重複');
                    break;
                } else {
                    // 如果名字没有出现过，将其添加到数组中
                    $seenNames[] = $name;
                }
            }

            $activity = $this->act;
            try {
                $htmlContent = "
                <html>
                <head>
                    <title>活动赠送门票通知</title>
                    <style>
                        /* 添加样式规则 */
                        body {
                            font-family: Arial, sans-serif;
                            margin: 0;
                            padding: 0;
                            background-color: #f4f4f4;
                        }
                        .container {
                            max-width: 600px;
                            margin: 0 auto;
                            padding: 20px;
                            background-color: #ffffff;
                            border-radius: 8px;
                            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                        }
                        h2 {
                            color: #333333;
                        }
                        p {
                            color: #666666;
                        }
                        ul {
                            list-style: none;
                            padding: 0;
                        }
                        li {
                            margin: 10px 0;
                        }
                        .event-header {
                            width: 100%;
                            height: auto;
                            border-radius: 8px;
                        }
                    </style>
                </head>
                <body>
                    <div class='container'>
                        <img src='{$activity['logo']}' alt='活动头图' class='event-header'>
                        <h2>您好！</h2>
                        <p>您已成功获得我们的活动赠送门票！以下是活动的详细信息：</p>
                        <ul>
                        <li><strong>名票名称：</strong> {$ticket_name}</li>
                        <li><strong>活动名称：</strong> {$activity['name']}</li>
                        <li><strong>活动时间：</strong> {$activity['begin_time']} -  {$activity['end_time']}</li>
                        <li><strong>活动形式：</strong> {$activity['type_name']}</li>
                        <li><strong>活动地点：</strong> {$activity['region_name']}{$activity['address_detail']}</li>
                        </ul>
                        <p>感谢您对我们的支持，期待在活动现场见到您！</p>
                        <p>祝您有愉快的一天！</p>
                    </div>
                </body>
                </html>
                ";
                foreach ($email_list as $key => $value) {
                    if(!$this->isValidEmailRegex($value['email'])) return $this->error('郵件格式不正確');
                    $res = EmailService::sendHtml($value['email'], "您的票券", $htmlContent);
                    if($res){
                        ActEamilLog::create([
                            'activity_id' => $id,
                            'name' => $value['name'],
                            'email' => $value['email'],
                            'phone' => $value['phone'],
                            'send_time' => date('Y-m-d H:i:s')
                        ]);
                    }
                    
                }
            } catch (\Exception $e) {
                 return $this->error($e->getMessage());
            }
            return $this->success('操作成功');
            
        }
        
    }

    private function isValidEmailRegex($email) {
        $pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
        return preg_match($pattern, $email);
    }
    /**
     * @name:活动通知
     * @author:Sam
     * @date:2024-04-11
     * @param:[string] param [desc]
    */
    public function user_active_par_notice($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        $this->id = $id;
        if(request()->isGet()){
            $this->list = ActEmailNotice::where('activity_id',$id)->where('status','in',[0,1])->order('id desc')->append(['status_name','front_time'])->select();
            $this->fetch();
        }else{
            $notice_id = input('post.notice_id/d',0);
            if($notice_id ==  0 ) return $this->error('請選擇通知');
            if(!$notice = ActEmailNotice::where('activity_id',$id)->where('id',$notice_id)->find())  return $this->error('通知不存在');
            $notice->status = 2;
            if($notice->save()) return $this->success('操作成功');
            return $this->error('操作失敗');
        }
        
    }
    
    public function allview($id){
        $this->act = $this->getActOrFail($id);
        $this->id = $id;
        $this->fetch();
    }

    public function overview($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        $this->act->append(['status_name','remain_ticket','ticket_count','type_name']);
        $this->article = $this->act->articleModel()->find();
        $this->ticket = $this->act->ticketModel()->find();
        $this->user   = $this->act->userModel()->field('id,name,email,profile')->find();
        $this->id = $id;
        $this->fetch();
    }

    /**
     * @name:活动预览
     * @author:Sam
     * @date:2024-04-14
     * @param:[string] param [desc]
    */
    public function user_allview_view($id){
        $this->act = $this->getActOrFail($id);
        $this->act->append(['type_name']);
        $this->act->themes = $this->act->themeModel()->select();
        $this->id = $id;
        $this->fetch();
    }

    /**
     * @name:基本资讯
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function content($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $this->fetch();
        }else{
            $data = request()->post();
            try {
                $this->validate($data,[
                    'abstract'          =>'require',
                    'desc'              =>'require',
                    'notice'            =>'require'
                ],[
                    'abstract.require'   =>'摘要不得为空',
                    'desc.require'       =>'简介不得为空',
                    'notice.require'     =>'注意事项不得为空',
                ]);
                $act = $this->getActOrFail($id);
                $act->setAttrs($data);
                $act->save();
            } catch (\Exception $e) {
                return  $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
    }

    /**
     * @name:支付方式
     * @author:Sam
     * @date:2024-04-11
     * @param:[string] param [desc]
    */
    public function pay($id)
    {
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->pay_type = explode(',',$this->act->pay_accept);
            $this->id = $id;
            $this->fetch();
        }else{
            $data = request()->post();
            try {
                $this->validate($data,[
                    'pay_type'          =>'require',
                ],[
                    'pay_type.require'   =>'支付方式不得为空',
                ]);
                $data['pay_accept'] = implode(',',$data['pay_type']);
                $act = $this->getActOrFail($id);
                $act->setAttrs($data);
                $act->save();
            } catch (\Exception $e) {
                return  $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
    }

    /**
     * @name:退款方式
     * @author:Sam
     * @date:2024-04-11
     * @param:[string] param [desc]
    */
    public function refund($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $this->refund = $this->act;
            $this->fetch();
        }else{
            $data = request()->post();
            try {
                $this->validate($data,[
                    'refund_type'          =>'require',
                ],[
                    'refund_type.require'   =>'退款方式不得为空',
                ]);
               
                $data['self_windows'] = input('post.self_windows','');
                $data['self_contact'] = input('post.self_contact','');
                $data['self_desc']    = input('post.self_desc','');
                $act = $this->getActOrFail($id);
                $act->setAttrs($data);
                $act->save();
            } catch (\Exception $e) {
                return  $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
    }

    /**
     * @name:嘉宾
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function guest($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $this->vo = ActActivityGuest::where('activity_id', $id)->order('sort asc')->select();
            $this->fetch();
        }else{
            if(request()->get('type') == 'sort'){
                $guestIds = input('post.ids/a');
                foreach ($guestIds as $index => $guestId) {
                    // 使用 Guest 模型更新排序字段
                    $guest = ActActivityGuest::find($guestId);
                    $guest->sort = $index + 1; // 索引从 0 开始，排序字段通常从 1 开始
                    $guest->save();
                }
                return $this->success('更新成功！');
            }else{
                $data = request()->post();
                try {
                    $this->validate($data,[
                        'username'          =>'require',
                        'posit'             =>'require',
                        'company_name'      =>'require',
                        'user_desc'         =>'require',
                        'profile'           =>'require',
                    ],[
                        'username.require'      =>'姓名不得为空',
                        'posit.require'         =>'职称不得为空',
                        'company_name.require'  =>'公司名称不得为空',
                        'user_desc.require'     =>'简介不得为空',
                        'profile.require'       =>'头像不得为空',
                    ]);
                    if(ActActivityGuest::where('activity_id', $id)->where('username',$data['username'])->count()) $this->exception('嘉宾已存在');
                    $data['activity_id'] = $id;
                    ActActivityGuest::create($data);
                } catch (\Exception $e) {
                    return  $this->error($e->getMessage());
                }
                return $this->success('更新成功！');
            }

        }
        
    }

    /**
     * @name:票券
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function ticket($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $ticket = ActActivityTicket::where('activity_id', $id)->find();
            if(!$ticket) $this->error('资源不存在');
            $ticket['tickets'] = ActTicketDetails::where('activity_id', $id)->select()->toArray() ?? [];;
            $ticket->is_on_salse = $ticket->sale_begin_timestamp <= time();
            $this->ticket = $ticket;
            // dump($this->vo);die;
            $this->fetch();
        } else {
            $data = $this->_vali([
                'desc.require'            => '票券說明必须！',
                'sale_begin.require'      => '售票開始時間必须！',
                'sale_end.require'        => '售票結束時間必须！',
                'ticket_yx_start.require' => '售票開始時間必须！',
                'ticket_yx_end.require'   => '售票開始時間必须！',
                'tickets.require'         => '門票設定不得為空'
            ]);
            if(!is_array($data['tickets'])) $this->error('門票格式不正確');
            if(!count($data['tickets'])) $this->error('至少需要一種門票');
            $name_counts = array_count_values(array_column($data['tickets'] , "name"));
            // 检查是否有出现次数大于1的name值
            foreach ($name_counts as $name => $count) {
                if ($count > 1) {
                    $this->error("票券名称不得重复: $name\n");
                }
            }
            foreach ($data['tickets'] as $key => $value) {
                if(!isset($value['name']) || trim($value['name']) == '')   $this->error('票名稱不得為空！');
                if(!isset($value['quantity']) || !$value['quantity']  > 0){
                    $value['quantity'] = 0;
                };
                if(!isset($value['is_open']) || $value['is_open']  !=1 ){
                    $value['is_open'] = 0;
                };
            }
            if (strtotime($data['sale_begin']) > strtotime($data['sale_end'])) {
                $this->error('售票开始时间不能大于结束时间！');
            }
            if (strtotime($data['ticket_yx_start']) > strtotime($data['ticket_yx_end'])) {
                $this->error('有效开始时间不能大于结束时间！');
            }
            $data['is_open']    = input('post.is_open',1);
            $data['is_verify']  = input('post.is_verify',0);
            $data['ticket_min'] = input('post.ticket_min',1);
            $data['ticket_max'] = input('post.ticket_max',1);
            $data['sale_begin_timestamp'] = strtotime($data['sale_begin']);
            $data['sale_end_timestamp']   = strtotime($data['sale_end']);
            $data['ticket_yx_start_timestamp'] = strtotime($data['ticket_yx_start']);
            $data['ticket_yx_end_timestamp']   = strtotime($data['ticket_yx_end']);
            try {
                $act = ActActivityTicket::where('activity_id', $id)->find();
                $act->setAttrs($data);
                $act->save($data);
                $ticket_details  = $data['tickets'];
                if(count($ticket_details)){
                    ActTicketDetails::where('activity_id',$id)->delete();
                    foreach ($ticket_details as $key => $value) {
                        ActTicketDetails::create([
                            'activity_id' => $id,
                            'ticket_id'   => $act->id,
                            'name'        => $value['name'],
                            'quantity'    => $value['quantity'],
                            'rest_quantity' => $value['quantity'],
                            'price'        => $value['price'],
                            'is_open'      => $value['is_open']
                        ]);
                    }
                } 
            } catch (\Exception $e) {
                 return $this->error($e->getMessage(),);
            } 
            $this->success('更新成功！');
        }
    }


        /**
     * @name:票卷分组
     * @author:Sam
     * @date:2024-04-05
     * @param:[string] param [desc]
    */
    public function group($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $group = ActTicketGroup::where('activity_id', $id)->select();
            if(!$group) return $this->error('资源不存在');
            $this->group = $group->toArray();
            $this->tickets = ActTicketDetails::where('activity_id',$id)->select();
            $this->fetch();
        } else {
            $type = input('type', 'add');
            if ($type ==='add') {
                $data = $this->_vali([
                    'group_name.require'          => '票券分組名稱必須！',
                    'group_number.require'        => '票券分組數量必須！',
                    'group_ticket.require'        => '票券必須！',
                    'group_price.require'         => '票券價格必須！',
                    'group_sale_begin.require'    => '票券銷售開始時間必須！',
                    'group_sale_end.require'      => '票券銷售結束時間必須！',
                    'group_yx_start_time.require' => '票券有效開始時間必須必須！',
                    'group_yx_end_time.require'   => '票券有效結束時間必須必須！',
                ]);
                $dgroup_ticket_key = request()->post('selected_ticket_key');
                $data['group_is_open']    = input('post.group_is_open',1);
                $data['group_is_verify']  = input('post.group_is_verify',0);
                //查找当前票券信息
                $exit_ticket  =  ActTicketDetails::where('activity_id',$id)->where('id',$data['group_ticket'])->find();
                if(!$exit_ticket) return $this->error('票券不存在');
                if(ActTicketGroup::where('activity_id', $id)->where('group_name',$data['group_name'])->count()) return $this->error('分组名称已存在');
                //查找该券已经分组的数量
                $total_exite_number  = ActTicketGroup::where('activity_id', $id)->where('ticket_id',$data['group_ticket'])->sum('group_number');
                if($total_exite_number + $data['group_number'] >= $exit_ticket['rest_quantity']) return $this->error('票券分組數量不得大於票券剩餘數量！');
                if (strtotime($data['group_sale_begin']) > strtotime($data['group_sale_end'])) {
                    $this->error('票券分组開始時間不能大於票券分组結束時間！');
                }
                if (strtotime($data['group_yx_start_time']) > strtotime($data['group_yx_end_time'])) {
                    $this->error('票券分组有效期開始時間不能大於票券分组有效期結束時間！');
                }
                $data['activity_id']         = $id;
                $data['ticket_id']           = $data['group_ticket'];
                $data['group_remain_number'] = $data['group_number'];
                $data['ticket_min'] = input('post.ticket_min',1);
                $data['ticket_max'] = input('post.ticket_max',1);
                $data['group_ticket'] = $exit_ticket->name;
                $data['group_desc'] = input('post.group_desc','');
                try {
                    if($group_id = request()->post('id/d',0) > 0){
                        dump($data);die;
                         ActTicketGroup::update($data);
                    }else{
                        ActTicketGroup::create($data);
                        $exit_ticket->rest_quantity -= $data['group_number'];
                        $exit_ticket->save();
                    }
                    
                } catch (\Exception $e) {
                     return $this->error($e->getMessage(),1);
                }
                return $this->success('操作成功');
            }elseif($type === 'edit'){
                $data = $this->_vali([
                    'id.require'                  => '票券分組必須！',
                    'group_name.require'          => '票券分組名稱必須！',
                    'group_price.require'         => '票券價格必須！',
                    'group_sale_begin.require'    => '票券銷售開始時間必須！',
                    'group_sale_end.require'      => '票券銷售結束時間必須！',
                    'group_yx_start_time.require' => '票券有效開始時間必須必須！',
                    'group_yx_end_time.require'   => '票券有效結束時間必須必須！',
                ]);
                $data['group_is_open']    = input('post.group_is_open',1);
                $data['group_is_verify']  = input('post.group_is_verify',0);
                if(ActTicketGroup::where('activity_id', $id)->where('id','<>',$data['id'])->where('group_name',$data['group_name'])->count()) return $this->error('分组名称已存在');
                if (strtotime($data['group_sale_begin']) > strtotime($data['group_sale_end'])) {
                    $this->error('票券分组開始時間不能大於票券分组結束時間！');
                }
                if (strtotime($data['group_yx_start_time']) > strtotime($data['group_yx_end_time'])) {
                    $this->error('票券分组有效期開始時間不能大於票券分组有效期結束時間！');
                }
                $data['activity_id']         = $id;
                $data['ticket_min'] = input('post.ticket_min',1);
                $data['ticket_max'] = input('post.ticket_max',1);
                $data['group_desc'] = input('post.group_desc','');
                try {
                    ActTicketGroup::update($data);
                    
                } catch (\Exception $e) {
                     return $this->error($e->getMessage(),1);
                }
                return $this->success('操作成功');
            }elseif($type === 'delete'){
                $ids = request()->post('ids','');
                if($ids == '') return $this->error('ID不得为空');
                if(ActTicketGroup::where('activity_id',$id)->where('id','in',$ids)->delete()) return $this->success('操作成功');
                return $this->error('操作失败');
            }
            return $this->error('操作失败');
            
        }
    }

    /**
     * @name:进阶设置
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function advanced($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $this->act = $this->getActOrFail($id);
            $this->fetch();
        }else{
            $data = request()->post();
            try {
                $this->validate($data,[
                    'un_public'                =>'require',
                    'show_tickets'             =>'require',
                ],[
                    'un_public.require'      =>'是否公开设置不得为空',
                    'show_tickets.require'    =>'是否显示余票设置不得为空',
                ]);
                $this->act->setAttrs($data);
                $this->act->save();
            } catch (\Exception $e) {
                return  $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
    }

    /**
     * @name:报名表
     * @author:Sam
     * @date:2024-04-10
     * @param:[string] param [desc]
    */
    public function diy($id){
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $this->act = $this->getActOrFail($id);
            $this->diyform = ActActivityDiy::where('activity_id',$id)->append(['options_arr'])->select();
            // dump($this->diyform);die;
            $this->fetch();
        }else{
            $data = request()->post();
            try {
                $this->validate($data,[
                    'diy'                =>'require',
                ],[
                    'diy.require'      =>'报名表不得为空',
                ]);
                $diy = json_decode($data['diy'],true);
                ActActivityDiy::where('activity_id',$id)->delete();
                foreach ($diy as $key => $value) {
                    ActActivityDiy::create([
                        'activity_id' => $id,
                        'label'       => $value['label'],
                        'must'        => $value['must'],
                        'label_type'  => $value['type'],
                        'tips'        => $value['tips'],
                        'desc'        => $value['desc'],
                        'options'     => $value['options']
                    ]);
                }
            } catch (\Exception $e) {
                return  $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
    }

    private function getActOrFail($id)
    {
        $uids = [$this->user['id']]; 
        if($this->user['pid'] > 0){
            array_push($uids,$this->user['pid']);
        }
        $act = ActActivity::where('id', $id)->where('create_user_id', 'in',$uids)->find();
        if (!$act) {
            $this->error('活动不存在！');
        }
        return $act;
    }

    public function theme($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        if ($this->request->isGet()) {
            $this->id = $id;
            $act = $this->getActOrFail($id);
            $this->themeList = ActSettingTheme::select();
            $this->themes = $act->themeModel()->column('theme_id');
            $this->fetch();
        } else {
            $data = $this->_vali(['theme.require' => '主题必须！', 'theme.array' => '选中主题必须是数组！', 'theme.length:1,2' => '最多选中两个！']);
            $act = $this->getActOrFail($id);
            $theme = $data['theme'];
            $act->saveActivityTheme($theme);
            $this->success('更新成功！');
        }

    }

    public function type($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        if ($this->request->isGet()) {
            $this->id = $id;
            $this->act = $this->getActOrFail($id);
            $this->typeList = ActSettingType::select();
            $this->fetch();
        } else {
            $data = $this->_vali(['type.require' => '类型必须！']);
            $act = $this->getActOrFail($id);
            $type = $data['type'];
            $act->type_id = $type;
            $act->save();
            $this->success('更新成功！');
        }
    }

    public function info($id)
    {
        if(!in_array(2,$this->user['roles'])) $this->error('没有权限');
        $this->act = $this->getActOrFail($id);
        if ($this->request->isGet()) {
            $this->id = $id;
            $this->typeList = ActSettingType::select();
            $this->regionTree = $this->getReginTree();
            $this->fetch();
        } else {
            $data = $this->_vali([
                'logo.require' => '活动图片必须！',
                'organizer_name.require' => '主办方名称必须！',
                'name.require' => '活动名称必须！',
                'begin_time.require' => '开始时间必须！',
                'end_time.require' => '结束时间必须！',
                'region_id.require' => '活动地区必须！',
                'address_detail.require' => '活动详细地址必须！',
            ]);
            if (strtotime($data['begin_time']) > strtotime($data['end_time'])) {
                $this->error('活动开始时间不能大于结束时间！');
            }
            $act = $this->getActOrFail($id);
            $act->setAttrs($data);
            $act->save();
            $this->success('更新成功！');
        }
    }

    private function getReginTree()
    {
        $region = Db::name('SystemRegion')->field('id,region_name as title,parent_id as pid')->select();
        //转化为树形结构
        return $this->array2Tree($region->toArray());

    }

    private function array2Tree($list, $pid = 0)
    {
        $tree = array();

        foreach ($list as $item) {
            if ($item['pid'] == $pid) {
                // 找到子节点
                $children = $this->array2Tree($list, $item['id']);
                // 如果有子节点，则添加到当前节点的children属性中
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                // 将当前节点添加到结果树中
                $tree[] = $item;
                // 从原始数组中移除已处理的节点，防止循环时重复处理
                unset($list[array_search($item, $list)]);
            }
        }

        return $tree;
    }

}